package com.jwdf.uda.ui.fragment.search;

import android.content.Context;
import android.os.Bundle;

import com.jwdf.uda.event.SearchInputEvent;
import com.jwdf.uda.ui.adapter.SearchRecordAdapter;
import com.jwdf.uda.ui.fragment.base.SimpleListFragment;
import com.jwdf.uda.utils.ConfigUtils;
import com.jwdf.uda.utils.EventBusUtil;

import java.util.ArrayList;
import java.util.Collections;

/**
 * Created by Administrator on 2016/5/20.
 */
public class SearchRecordFragment extends SimpleListFragment {
    private SearchRecordAdapter mAdapter;
    private SearchHotFragment mSearchHistory;

    public static SearchRecordFragment instance(ArrayList<String> records) {
        SearchRecordFragment view = new SearchRecordFragment();
        Bundle args = new Bundle();
        args.putStringArrayList("records", records);
        view.setArguments(args);
        return view;
    }

    @Override
    protected void initViews() {
        ArrayList<String> records = getArguments().getStringArrayList("records");
        mAdapter = new SearchRecordAdapter(getContext());
        mAdapter.setOnRecordItemClickListener(createOnRecordItemListener());
        boolean showTitle = records.size() > 0;
        mSearchHistory = createSearchHistory(getContext(), showTitle);
        mDataBinding.commonFragmentList.addHeaderView(mSearchHistory);
        mDataBinding.commonFragmentList.setAdapter(mAdapter);
        mAdapter.setData(records);
    }

    private SearchHotFragment createSearchHistory(Context context, boolean showTitle) {
        SearchHotFragment menu = new SearchHotFragment(context, showTitle);
        return menu;
    }

    @Override
    protected boolean canPullRefresh() {
        return false;
    }

    @Override
    protected void onListItemClick(int position) {
        if (position >= 0) {
            EventBusUtil.post(new SearchInputEvent(mAdapter.getItem(position)));
        }
    }

    @Override
    protected void requestData(boolean refresh) {

    }

    private SearchRecordAdapter.OnRecordItemClickListener createOnRecordItemListener() {
        return new SearchRecordAdapter.OnRecordItemClickListener() {
            @Override
            public void onItemClick(String item) {
                mAdapter.remove(item);
                String userId = ConfigUtils.getUserId(getContext());
                ArrayList<String> items = ConfigUtils.restoreStringArray(getContext(), userId, true);
                items.remove(item);
                Collections.reverse(items);
                ConfigUtils.saveStringArray(getContext(), userId, items);
                mSearchHistory.showHistoryTitle(!mAdapter.isEmpty());
            }
        };
    }
}
